package com.ambercrm.business.main.fragment;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ambercrm.R;
import com.ambercrm.base.BaseFragment;
import com.ambercrm.base.MyApplication;
import com.ambercrm.beans.CommonClass;
import com.ambercrm.business.AccountCheckActivity;
import com.ambercrm.business.ChangePasswordActivity;
import com.ambercrm.business.UserInfoActivity;
import com.ambercrm.business.bean.AuthBean;
import com.ambercrm.business.bean.EmpIeeUserInfo;
import com.ambercrm.business.bean.LoginUserInfo;
import com.ambercrm.business.bean.MyUserInfo;
import com.ambercrm.business.login.LoginActivity;
import com.ambercrm.business.main.MainActivity;
import com.ambercrm.common.Common;
import com.ambercrm.constant.Constant;
import com.ambercrm.constant.UrlConstant;
import com.ambercrm.eventbus_event.LogoutEvent;
import com.ambercrm.eventbus_event.UpdateHeaderEvent;
import com.ambercrm.tools.EmptyUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends BaseFragment implements View.OnClickListener {

    private TextView tvUserName;
    private TextView tvUserAccount;
    private TextView tvUserTelephone;
    private ImageView ivUserIcon;
    private RelativeLayout rlUserInfo;
    private RelativeLayout rlChangePassword;
    private RelativeLayout rlLoginOut;
    private LoginUserInfo userInfo;
    private RelativeLayout rlDisplayInfo;
    private TextView tvDisplayName;
    private EmpIeeUserInfo empInfo;
    String mRealName;

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        tvUserName = findView(view, R.id.tv_user_name);
        tvUserAccount = findView(view, R.id.tv_user_account);
        tvUserTelephone = findView(view, R.id.tv_user_telephone);
        ivUserIcon = findView(view, R.id.iv_user_icon);
        rlUserInfo = findView(view, R.id.rl_user_info);
        rlChangePassword = findView(view, R.id.rl_change_password);
        rlLoginOut = findView(view, R.id.rl_login_out);
        rlDisplayInfo = findView(view, R.id.rl_display_info);
        tvDisplayName = findView(view, R.id.tv_display_name);
        rlUserInfo.setOnClickListener(this);
        rlChangePassword.setOnClickListener(this);
        rlLoginOut.setOnClickListener(this);
        mRealName = sp.getValue(Constant.sp_realName);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getUserInfo();
    }

    private void getUserInfo() {
        HashMap<String, Object> params = new HashMap<>();
        String registId = sp.getValue("push_regist_id");
        if (registId != null) {
            params.put("pushId", registId);
        }
        httpPost(UrlConstant.EMPLOYEE_SYNC, 0, params, false, "");
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.rl_user_info) {
            if (empInfo != null) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("empInfo", empInfo);
                startActivity(UserInfoActivity.class, bundle, false);
            }
        } else if (id == R.id.rl_change_password) {
            startActivity(AccountCheckActivity.class, null, false);
        } else if (id == R.id.rl_login_out) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setTitle("提示");
            builder.setMessage("确定退出登录？");
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    rlLoginOut();
                }
            });
            Dialog dialog = builder.create();
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        }
    }

    private void rlLoginOut() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("token", sp.getValue(Constant.sp_Token));
        params.put("isapp", true);
        httpPost(UrlConstant.LOGOUT_URL, 1, params, false, "");
    }

    @Override
    protected void onSucceed(String result, int what) {
        super.onSucceed(result, what);
        try {
            if (what == 0) {
                Gson mGson = new Gson();
                MyUserInfo myUserInfo = mGson.fromJson(result, MyUserInfo.class);
//                CommonClass<LoginUserInfo> commonClass = mGson.fromJson(result, new TypeToken<CommonClass<LoginUserInfo>>() {
//                }.getType());
//                if (commonClass.getCode() == 0) {
//                    if (commonClass.getResult() != null) {
//                        userInfo = commonClass.getResult();
//                        AuthBean auth = userInfo.getAuth();
//                        tvUserName.setText(auth.getDisplay());
//                        tvUserAccount.setText(auth.getName());
//                        tvUserTelephone.setText(auth.getTelphone());
//                        if (EmptyUtils.notEmpty(auth.getDisplay())) {
//                            ivUserIcon.setVisibility(View.GONE);
//                            rlDisplayInfo.setVisibility(View.VISIBLE);
//                            tvDisplayName.setText(auth.getDisplay());
//                        }
//                    }
//                }
                if (myUserInfo.getCode() == 0) {
                    if (myUserInfo.getResult() != null) {
                        if (myUserInfo.getResult().getEmpInfo() != null) {
                            empInfo = myUserInfo.getResult().getEmpInfo();
                            tvUserName.setText(mRealName);
                            tvUserAccount.setText(empInfo.getAccount());
                            tvUserTelephone.setText(empInfo.getPhone());
                            if (EmptyUtils.notEmpty(empInfo.getAvatar())) {
                                ivUserIcon.setVisibility(View.VISIBLE);
                                rlDisplayInfo.setVisibility(View.GONE);
                                MyApplication.getApplicationInstance().displayImg(empInfo.getAvatar()+"?token="+ Common.getInstance().getToken(), ivUserIcon);
                            } else {
                                if (EmptyUtils.notEmpty(mRealName)) {
                                    ivUserIcon.setVisibility(View.GONE);
                                    rlDisplayInfo.setVisibility(View.VISIBLE);
                                    int lenght = empInfo.getUsername().length();
                                    tvDisplayName.setText(mRealName.substring(lenght-2, lenght));
                                }
                            }
                        }
                    }
                }
            } else if (what == 1) {
                JSONObject object = new JSONObject(result);
                String code = object.optString("code");
                if ("0".equals(code)) {
                    sp.deleteValue(mActivity, Constant.sp_Token);
                    startActivity(LoginActivity.class, null, true);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onEventMainThread(UpdateHeaderEvent event) {
        if (empInfo != null) {
            empInfo.setAvatar(event.getMsg());
            MyApplication.getApplicationInstance().displayImg(empInfo.getAvatar()+"?token="+ Common.getInstance().getToken(), ivUserIcon);
        }
    }
}
